package com.qys.livesMall.file.server.upload.utils;

import com.qys.livesMall.common.utils.QysDateUtil;
import com.qys.livesMall.file.server.upload.enums.FileEnum;
import com.qys.livesMall.framework.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;

import java.util.HashMap;
import java.util.Map;

/**
 * @menu FilePathUtil
 * @date 2023/05/25 14:49
 */
public class FilePathUtil {

    /**
     *
     * @param fileEnum
     * @param userId null 为当前用户Id
     * @return
     */
    public static String buildPath(FileEnum fileEnum, Long userId){
        String template=fileEnum.getPath();
        if (StringUtils.isBlank(template)){
            return null;
        }
        Map<String,Object> params=getParam(userId);

        ExpressionParser parser = new SpelExpressionParser();
        TemplateParserContext parserContext = new TemplateParserContext();
        String shopContract = parser.parseExpression(template,parserContext).getValue(params, String.class);
        return shopContract;
    }

    private static Map<String,Object> getParam(Long userId){
        Map<String, Object> params = new HashMap<>();
        params.put("datePath", QysDateUtil.datePath());
        if (userId==null){
            userId=SecurityUtils.getUserId();
        }
        params.put("userId", userId);
        String userIdStr= String.valueOf(userId);
        if (userIdStr.length()==1){
            userIdStr="0"+userIdStr;
        }
        params.put("userIdTop2", userIdStr.substring(0,2));


        return params;

    }

}

